import {
	baseURL
} from "@/utils/global_variable.js"
import api from "@/utils/api.js"
// uni-app请求封装
export default class Request {
	http(router, data = {}, method, tip) {
		// 基础地址
		let path = baseURL;
		// path='http://bonfirenight.nat300.top';
		//path="https://dx.daidaixiong.net";
		 //path="http://192.168.0.105:8082";
		
		// 返回promise
		return new Promise((resolve, reject) => {
			if (tip == "" || tip == null || tip == undefined) {
				tip = '正在加载中';
			}
			uni.showLoading({
				title: tip,
				mask: true
			})
			// 请求
			uni.request({
				url: `${path}${router}`,
				header: {
					"token": uni.getStorageSync('token'),
					// "Content-Type": "application/json"
					"Content-Type": method == 'GET' ? "application/json" : method == 'POST' ?
						'application/json;charset=UTF-8' : "application/x-www-form-urlencoded"
				},
				data: data,
				method: method == 'POSTS' ? 'POST' : method,
				// dataType:'json',
				success: res => {
					uni.hideLoading();
					if (res.statusCode != 200) {
						let code = res.data.code;
						if (code != null && code != undefined && code != "") {
							res.data.msg = "接口错误";
							code = 401;
						}
						if(code==2003){
							if(!api.getTokenOutSave()){
								api.setTokenOutSave("1");
								uni.showModal({
									title: '',
									content: '登录失效,请重新登录！',
									showCancel: false, //隐藏取消按钮
									success(res) {
										api.setToken("");
										uni.navigateTo({
											url: '/pages/login/index',
											success:function(res){
												api.setTokenOutSave("");
											}
										})
									}
								})
							}
						}else{
							uni.showModal({
								title: '',
								content: res.data.msg,
								showCancel: false, //隐藏取消按钮
								success(res) {
									return false;
								}
							})
						}
						return;
					} else {
						if (res.data.code != 0) {
							let code = res.data.code;
							let msg=res.data.msg;
							if (code == null || code == undefined || code == "") {
								msg = "接口错误";
								code = 401;
							} 
							if (code == 2003) {
								if(!api.getTokenOutSave()){
									api.setTokenOutSave("1");
									uni.showModal({
										title: '',
										content: '登录失效,请重新登录！',
										showCancel: false, //隐藏取消按钮
										success(res) {
											api.setToken("");
											uni.navigateTo({
												url: '/pages/login/index',
												success:function(res){
													api.setTokenOutSave("");
												}
											})
										}
									})
								}
								
							} else {
								uni.showModal({
									title: '',
									content: msg,
									showCancel: false, //隐藏取消按钮
									success(res) {
										return false;
									}
								})
							}

							return;
						} else {
							resolve(res.data);
						}
					}
				},
				fail: res => {
					uni.hideLoading();
					resolve({
						code: 1,
						msg: '接口错误',
						data: null
					});

				}
			})
		})
	}
}
